package com.wishwall.persistence.managers;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;

import com.wishwall.persistence.PersistenceContext;

/**
 * 
 * @author yavor.gologanov
 *
 */
public abstract class AbstractBeanManager {

	private PersistenceContext persistenceContext = null;

	/**
	 * 
	 * @param entityManager
	 */
	protected AbstractBeanManager(PersistenceContext persistenceContext) {
		this.persistenceContext = persistenceContext;
	}

	/**
	 * 
	 */
	protected EntityManager getEntityManager() {
		return persistenceContext.getEntityManager();
	}


	/**
	 * 
	 * @return
	 */
	protected PersistenceContext getPersistenceContext() {
		return persistenceContext;
	}

	/**
	 * 
	 * @param entity
	 */
	protected <T> void storeEntity(T entity) {

		getEntityManager().persist(entity);
		getEntityManager().flush();

	}

	/**
	 * 
	 * @param entity
	 */
	protected <T> void deleteEntity(T entity) {

		T attachedEntity = getEntityManager().merge(entity);
		getEntityManager().remove(attachedEntity);

	}

	/**
	 * 
	 * @param entity
	 */
	protected <T> void updateEntity(T entity) {

		T attachedEntity = getEntityManager().merge(entity);
		getEntityManager().persist(attachedEntity); //? dali e nujno

	}


	/**
	 * @param clazz
	 * @param idValue
	 * @return
	 */
	protected <T> T findEntity(Class<T> clazz, Object idValue) {
		T bean = getEntityManager().find(clazz, idValue);
		if (bean == null) {
			throw new EntityNotFoundException("The bean " + clazz.getName() + " with id " + idValue + " does not exist!");
		}
		return bean;
	}

	/**
	 * 
	 * @param selectQuery
	 * @param limit
	 * @param parameters
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected <T> List<T> findAllEntities(String selectQuery, int limit, Object... parameters) {

		Query query = getEntityManager().createQuery(selectQuery);
		if (parameters != null  && parameters.length > 0) {
			for (int i = 0; i < parameters.length; i += 2) {
				String parameterName = (String)parameters[i];
				Object parameterValue = parameters[i + 1];

				query.setParameter(parameterName, parameterValue);
			}
		}
		if(limit > 0) {
			query.setMaxResults(limit);
		}

		return (List<T>) query.getResultList();

	}


}
